<template>
  <div class="container">
    <div class="g-flx wraper">
      <!-- 左侧喊话内容 -->
      <div>
        <el-row v-if="demoList && demoList.length">
          <el-col :span="4">喊话示例：</el-col>
          <el-col :span="20">
            <el-button :class="{'active': curOrderPosition === Number(index)}" v-for="(item, index) in demoList" :key="index" @click="searchPosition(index)">{{ item }}</el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="4">喊话内容：</el-col>
          <el-col :span="15" class="last-days">
            <el-input v-model="shoutsContent" @input="validContent"></el-input>
            <div class="tips" v-if="showTips">{{ tipContent }}</div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="4">剩余天数：</el-col>
          <el-col :span="20" class="last-days"><span>{{ maxLength }}天</span></el-col>
        </el-row>

        <h4 style="font-size: 18px;">喊话时间</h4>
        <el-card>
          <calendar v-model="time" :range="range" :disabledDays="disabledDays" :maxLength="maxLength" :checkedDate="checkedDate" ref="calendar">
            <template #footer>
              <p class="active-days">生效天数 <span>{{ chooseNum }}</span> 天</p>
              <p>活动时间：{{ startTime }} 至 {{ endTime }}</p>
            </template>
          </calendar>
        </el-card>
      </div>

      <!-- 右侧图片 -->
      <div style="padding-left: 30px">
        <div class="right-wrap">
          <div class="title">温馨提示</div>
          <div class="list"><span>* </span>站长喊话：请简要用一句话描述喊话的内容</div>
          <div class="list"><span>* </span>站长喊话：请勿填写降价类型等内容</div>
          <div class="list"><span>* </span>字数限制： <span>30字以内</span></div>
          <!-- <div class="list"><span>* </span>站长喊话将会提交给团油进行审核，<span>一般1-2工作日内审核完成</span></div> -->
        </div>
        <div class="effect">
          <h3>APP效果演示</h3>
          <img :src="`${this.$ossUrl}market/shoutEffect.png`" alt="">
        </div>
      </div>
    </div>

    <div class="btn-group">
      <el-button @click="$router.go(-1)">返回</el-button>
      <el-button @click="submit" type="primary">提交</el-button>
    </div>
  </div>
</template>
<script>
import calendar from '@/components/work/calendar'
import { getDemoList, getShoutLeftDays, addShouts, updateShouts, shoutsDetail } from '@/api/marketShop/masterShouts'
import { mapGetters } from 'vuex'
import dayjs from 'dayjs'

export default {
  name: 'setOrder',
  components: {
    calendar
  },
  data () {
    return {
      range: [], // 可用日期范围
      disabledDays: [], // 不可选日期，需要转换为”月-日“
      maxLength: 0, // 可选日期最大值
      chooseNum: 0, // 已选天数
      startTime: '', // 选择开始日期
      endTime: '', // 选择结束日期
      time: {
        startTime: '',
        endTime: ''
      },
      shoutsContent: '',
      edit: false,
      checkedDate: [], // 设置已选中的日期
      activeId: null, // 活动ID
      curOrderPosition: null, // 当前选中的位置
      demoList: [],
      showTips: false,
      tipContent: ''
    }
  },
  computed: {
    ...mapGetters(['gasInfo'])
  },
  watch: {
    time: {
      deep: true,
      handler (val) {
        if (!val.startTime || !val.endTime) return
        this.chooseNum = Math.floor((val.endTime - val.startTime) / (24 * 3600 * 1000)) + 1
        const startTime = this.whetherChooseToday(val.startTime) ? dayjs() : dayjs(val.startTime)
        this.startTime = startTime.format('YYYY-MM-DD HH:mm:ss')
        this.endTime = this.formatDate(val.endTime, 'end')
      }
    }
  },
  methods: {
    // 初始化日历
    async initCalendar () {
      try {
        const {code, result: {leftDays, days, unAvaliableDays}} = await getShoutLeftDays({ gasId: this.gasInfo.gasId })
        if (code !== 200) return
        this.maxLength = this.edit ? leftDays + this.chooseNum : leftDays
        // 如果是修改，需要在这里把不可选日期里的已选中日期移除
        if (this.edit) {
          const startTime = dayjs(dayjs(this.startTime).format('YYYY-MM-DD 00:00:00')).valueOf()
          const endTime = dayjs(this.endTime).valueOf()
          for (let i = unAvaliableDays.length; i >=0; i--) {
            if (unAvaliableDays[i] > endTime || unAvaliableDays[i] < startTime) {
              this.disabledDays.push(dayjs(unAvaliableDays[i]).format('MM-DD'))
            }
          }
        } else {
          this.disabledDays = unAvaliableDays.map(item => dayjs(item).format('MM-DD'))
          // 如果是新增，默认自动选中第一个可选日期
          // const firstDay = this.getFirstChooseDate(days)
          // if (firstDay) {
          //   this.checkedDate = [firstDay, firstDay]
          //   this.startTime = this.formatDate(firstDay)
          //   this.endTime = this.formatDate(firstDay, 'end')
          //   this.time = {
          //     startTime: dayjs(this.startTime).valueOf(),
          //     endTime: dayjs(this.endTime).valueOf()
          //   }
          // }
        }
        this.range[0] = new Date(+new Date())
        this.range[1] = new Date(+new Date() + (days - 1) * 24 * 3600 * 1000)
        this.$nextTick(() => {
          this.$refs.calendar.clearChooseRange()
          this.$refs.calendar.initCalendar()
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 获取第一个可选日期
    getFirstChooseDate (days) {
      let day = dayjs(),
          i = 0

      const findDay = (day) => {
        if (!this.disabledDays.includes(day.format('MM-DD'))) {
          return dayjs(day.format('YYYY-MM-DD 00:00:00')).valueOf()
        } else if (i < days) {
          i++
          return findDay(day.add(1, 'day'))
        } else {
          return false
        }
      }
      return findDay(day)
    },
    // 获取喊话示例
    async getDemoList () {
      try {
        const {code, result} = await getDemoList()
        if (code !== 200) return
        this.demoList = result
      } catch (error) {
        console.log(error)
      }
    },
    // 点击按钮
    searchPosition (index) {
      this.curOrderPosition = index
      this.shoutsContent = this.demoList[index]
      this.showTips = false
    },
    async submit () {
      if (!this.validContent()) return
      if (!this.time.startTime || !this.time.endTime) {
        this.$message({
          message: '请选择活动时间',
          type: 'error'
        })
        return
      }
      this.edit ? this.editHttp(1) : this.addHttp(1)
    },
    // 校验喊话内容
    validContent () {
      if (!this.shoutsContent) {
        this.tipContent = '请输入喊话内容，最多30字符'
      } else if (this.shoutsContent.length > 30) {
        this.tipContent = '喊话内容超过30字符'
      } else {
        this.tipContent = '输入内容格式错误'
      }
      const valid = /^[\u4e00-\u9fa50-9A-Za-z,，、!！。.]{1,30}$/.test(this.shoutsContent)
      this.showTips = !valid
      return valid
    },
    // 调用新增接口
    async addHttp (filter) {
      try {
        const {code, message} = await addShouts({
          gasId: this.gasInfo.gasId,
          content: this.shoutsContent,
          startTime: this.whetherChooseToday(this.time.startTime) ? this.formatDate(new Date()) : this.formatDate(this.time.startTime),
          endTime: this.formatDate(this.time.endTime, 'end'),
          filter
        })
        if (code === 1111) {
          this.$confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.addHttp(0)
          }).catch(() => {})
        } else if (code !== 200) {
          this.$message({
            message,
            type: 'error'
          })
          this.initCalendar()
        } else {
          this.$message({
            message: '配置成功',
            type: 'success'
          })
          this.$router.push({ path: '/marketCenter/activitySuccess' })
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 修改接口
    async editHttp (filter) {
      try {
        const {code, message} = await updateShouts({
          activityId: this.activeId,
          gasId: this.gasInfo.gasId,
          content: this.shoutsContent,
          startTime: this.whetherChooseToday(this.time.startTime) ? this.formatDate(new Date()) : this.formatDate(this.time.startTime),
          endTime: this.formatDate(this.time.endTime, 'end'),
          filter
        })
        if (code === 1111) {
          this.$confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.editHttp(0)
          }).catch(() => {})
        } else if (code !== 200) {
          this.$message({
            message,
            type: 'error'
          })
          this.getOrderData()
        } else {
          this.$message({
            message: '配置成功',
            type: 'success'
          })
          this.$router.push({ path: '/marketCenter/activitySuccess' })
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 获取反显数据
    async getOrderData () {
      try {
        const { code, result: { content, startTime, endTime } } = await shoutsDetail({activityId: this.activeId})
        if (code !== 200) return
        this.shoutsContent = content
        this.chooseNum = Math.floor((endTime - startTime) / (24 * 3600 * 1000) + 1)
        this.time = {
          startTime,
          endTime
        }
        this.startTime = this.formatDate(startTime)
        this.endTime = this.formatDate(endTime, 'end')
        await this.initCalendar()
        this.checkedDate = [new Date(startTime), new Date(endTime)]
        this.$nextTick(() => {
          this.$refs.calendar.initCalendar()
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 检查是否选择了当前日期
    whetherChooseToday (time) {
      return dayjs(time).format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD')
    },
    // 格式化时间
    formatDate (date, type) {
      return type !== 'end' ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : dayjs(date).format('YYYY-MM-DD 23:59:59')
    }
  },
  created () {
    this.getDemoList()
    if (this.$route.query.activeId) {
      this.activeId = this.$route.query.activeId
      this.edit = true
      this.getOrderData()
      return
    }
    this.initCalendar()
  }
}
</script>
<style lang="less" scoped>
  .container {
    width: 100%;
    font-size: 14px;
    color: #333333;
    background: #fff;
    margin: 10px;
    padding: 24px 20px;
    .wraper {
      &>div{
        width: 50%;
        .el-row {
          color: #333333;
          line-height: 60px;
          .last-days {
            color: #333333;
            font-weight: 600;
            span {
              color: #4B7EFE;
            }
            .tips  {
              color: red;
              font-weight: 400;
              margin-top: -20px;
            }
          }
        }
      }
      .active-days {
        margin-top: 30px;
        font-size: 18px;
        font-weight: 600;
        color: #333333;
        span {
          font-size: 24px;
          color: #4B7EFE;
        }
        &+p {
          color: #999999;
        }
      }
      .el-button {
        height: 30px;
        line-height: 30px;
        padding: 0 10px;
        border: 1px solid #4765F9;
        color: #4765F9;
        background: rgba(71, 101, 249, 0.09);
        margin-left: 0;
        margin-right: 20px;
      }
      .active {
        background: #4B7EFE;
        color: #fff;
        border-radius: 4px;
      }
    }
    .right-wrap {
      background: rgba(71, 101, 249, 0.05);
      border-radius: 10px;
      margin-left: 30px;
      margin-right: 20px;
      padding: 24px 32px;
      .title {
        font-size: 18px;
        font-weight: 600;
        color: #4B7EFE;
        margin-bottom: 20px;
      }
      .list {
        font-size: 14px;
        color: #666666;
        line-height: 30px;
        span {
          color: #E31837;
        }
      }
    }
    .effect {
      h3 {
        margin-left: 50px;
        padding: 10px 0;
      }
      img {
        margin-left: 20px;
        width: 70%;
      }
    }
    .btn-group {
      margin-top: 30px;
      /deep/.el-button {
        width: 125px;
      }
    }
  }
</style>